/*
 * eiam-console - Employee Identity and Access Management
 * Copyright © 2022-Present Jinan Yuanchuang Network Technology Co., Ltd. (support@topiam.cn)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import { RESULT_STATE } from '@/constant';
import {
  AlertOutlined,
  AndroidOutlined,
  LockOutlined,
  PaperClipOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { LoginFormPage, ProFormText } from '@ant-design/pro-components';
import { useRequest } from 'ahooks';
import { Alert, App, Button, Form, Input, Modal, Radio } from 'antd';
import React, { useState, useEffect } from 'react';
import { FormattedMessage, Helmet, history, setLocale, useIntl, useModel } from '@umijs/max';
import queryString from 'query-string';
import { flushSync } from 'react-dom';
import classnames from 'classnames';
import CryptoJS from 'crypto-js';
import useStyle from './style';
import './Login.less';
import {
  setToken,
  setId,
  removeToken,
  removeId,
  removeLock,
  setPwd,
  removePwd,
} from '@/utils/token';

import PageLoading from '@/components/PageLoading';
import { getCaptCha, postSiteAccountLogin } from './request';
import Register from './Register';
import bgc from '@/pages/images/bgc.jpg';
const prefixCls = 'login';
// const showBanner = process.env.PREVIEW_ENV || process.env.NODE_ENV === 'development';

/**
 * 错误消息
 *
 * @param content
 * @constructor
 */
const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => <Alert message={content} type="error" showIcon />;
const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<{ message: string; status: string }>();
  const { initialState, setInitialState } = useModel('@@initialState');
  const [form] = Form.useForm();
  const intl = useIntl();
  const { message } = App.useApp();
  const { styles } = useStyle(prefixCls);
  /** 加载状态 */
  const [statusLoading, setStatusLoading] = useState<boolean>(false);
  /**
   * 获取用户信息
   */
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        // prettier-ignore
        setInitialState((s: any) => ({ ...s, currentUser: userInfo }));
      });
    }
  };

  const goto = () => {
    if (!history) return;
    const query = queryString.parse(history.location.search);
    const { redirect_uri } = query as { redirect_uri: string };
    window.location.replace(redirect_uri || '/');
    return;
  };

  const [captchaUrl, setCaptchaUrl] = useState('');
  const [cid, setcid] = useState('');
  useEffect(() => {
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    getcaptcha();

    // 不管什么情况进入登录页面---清除token--清除用户id---清除锁屏状态--清除登录用户密码---清除登录用户信息
    removeToken();
    removeId();
    removeLock();
    removePwd();
    localStorage.removeItem('userInfo');

    ReadFile();
  }, []);

  const ReadFile = () => {
    window.electronAPI.readConfig().then((res) => {
      console.log(res);

      setLocale(res.umi_locale, false);
        localStorage.setItem('IP', res.ServiceIp);
    });
  };

  const [inputValue, setInputValue] = useState(''); // 创建一个状态变量

  const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(event.target.value); // 当输入框的值改变时，更新状态变量
  };
  const getcaptcha = async () => {
    const res = await getCaptCha();
    setCaptchaUrl(res.data.base64);
    setcid(res.data.cid);
  };
  const defaultKey = 'f080a463654b2279';
  const aesEcb = {
    // 加密
    encrypt(word: string, keyStr: string = defaultKey): string {
      const key = CryptoJS.enc.Utf8.parse(keyStr);
      const src = CryptoJS.enc.Utf8.parse(word);
      const encrypted = CryptoJS.AES.encrypt(src, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
      });
      return encrypted.toString();
    },
    // 解密
    decrypt(word: string, keyStr: string = defaultKey): string {
      const key = CryptoJS.enc.Utf8.parse(keyStr);
      const decrypt = CryptoJS.AES.decrypt(word, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
      });
      return CryptoJS.enc.Utf8.stringify(decrypt).toString();
    },
  };
  const handleSubmit = async (values: API.LoginParamsType): Promise<boolean | void> => {
    let pwd = aesEcb.encrypt(values.password);
    let data = {
      username: values.username,
      password: pwd,
      cid: cid,
      code: inputValue,
      isLock: false,
    };
    const res: any = await postSiteAccountLogin(data);
    console.log(res);

    if (res.code !== 0) {
      getcaptcha();
      return message.error(intl.formatMessage({ id: 'pages.login.login-error' }));
    }
    setToken(res.data.token);
    sessionStorage.setItem('token', res.data.token);
    setId(res.data.id);
    message.success(intl.formatMessage({ id: 'pages.login.success-prompt' }));

    setPwd(values.password);
    setTimeout(() => {
      fetchUserInfo();
      localStorage.setItem('SEND_TYPE', Radiovalue === 1 ? 'HTTP' : 'DLL');
    
      goto();
    }, 500);
    return true;
  };
  const { data, loading, run } = useRequest(handleSubmit, {
    debounceWait: 0,
    manual: true,
  });

  const [IsRegister, setIsRegister] = useState(false);

  const [Radiovalue, setRadiovalue] = useState(1);

  return (
    <>
      {IsRegister ? (
        <Register setIsRegister={setIsRegister} />
      ) : (
        <div>
          <div className={styles.main}>
            {!statusLoading ? (
              <>
                <Helmet>
                  <link rel="icon" href={'/favicon.ico'} />
                </Helmet>
                {/* {showBanner && <Banner />} */}
                <div className={classnames(`${prefixCls}`)}>
                  <div
                   
                  >
                    {/* 登录表单左侧 */}
                    {/* <div className="login-left">
                <h1 style={{ fontSize: '40px' }}>七天联网锁智能系统</h1>
                <img src="/login-background1.png" alt=""                    ,/>
              </div> */}
                    <LoginFormPage
                      // logo={'http://110.41.181.121:8001/pz4.jpg'}
                      backgroundImageUrl={bgc}
                      // title="七天酒店网联锁系统"
                      initialValues={{
                        'remember-me': false,
                        username: '13712345678',
                        password: '123456',
                      }}
                      title={intl.formatMessage({ id: 'pages.login.title' })}
                      containerStyle={{
                        // backgroundColor: 'rgba(0, 0, 0,0.7)',
                        backdropFilter: 'blur(4px)',
                      }}
                      form={form}
                      scrollToFirstError
                      submitter={{
                        searchConfig: {
                          submitText: intl.formatMessage({
                            id: 'pages.login.submit',
                          }),
                        },
                        render: (_, dom) => dom.pop(),
                        submitButtonProps: {
                          loading,
                          size: 'large',
                          style: {
                            width: '100%',
                          },
                        },
                      }}
                      onFinish={async (values) => {
                        run(values);
                        return data;
                      }}
                    >
                      <div
                        style={{ marginBottom: '30px', fontWeight: 'bold', marginTop: '40px' }}
                      ></div>
                      {userLoginState?.status !== RESULT_STATE.SUCCESS &&
                        userLoginState?.message && (
                          <>
                            <LoginMessage content={userLoginState?.message} />
                            <br />
                          </>
                        )}

                      <>
                        <div style={{marginBottom: '10px'}}>
                          <div style={{fontSize:16,fontWeight:550,marginBottom:5}}>发卡模式</div>
                          <Radio.Group
                            value={Radiovalue}
                            onChange={(e) => {
                              setRadiovalue(e.target.value);
                            }}
                          >
                            <Radio value={1}>HTTP</Radio>
                            <Radio value={2}>DLL</Radio>
                          </Radio.Group>
                        </div>
                        <ProFormText
                          name="username"
                          label="账号"
                          fieldProps={{
                            size: 'large',
                            prefix: (
                              <UserOutlined
                                className={classnames(`${prefixCls}-form-prefix-icon`)}
                              />
                            ),
                            autoComplete: 'off',
                          }}
                          placeholder={intl.formatMessage({
                            id: 'pages.login.username.placeholder',
                          })}
                          rules={[
                            {
                              required: true,
                              message: <FormattedMessage id="pages.login.username.required" />,
                            },
                          ]}
                        />
                        <ProFormText.Password
                          name="password"
                          label="密码"
                          fieldProps={{
                            size: 'large',
                            autoComplete: 'new-password',
                            prefix: (
                              <LockOutlined
                                className={classnames(`${prefixCls}-form-prefix-icon`)}
                              />
                            ),
                          }}
                          placeholder={intl.formatMessage({
                            id: 'pages.login.password.placeholder',
                          })}
                          rules={[
                            {
                              required: true,
                              message: <FormattedMessage id="pages.login.password.required" />,
                            },
                          ]}
                        />
                        <div
                          style={{
                            marginBottom: '15px',
                            display: 'flex',
                            justifyContent: 'center',
                          }}
                        >
                          <Input
                            placeholder={intl.formatMessage({
                              id: 'pages.login.verification-code',
                            })}
                            value={inputValue}
                            onChange={handleInputChange}
                            style={{ width: '190px', height: '40px', marginRight: '40px' }}
                          />
                          <img
                            src={captchaUrl}
                            alt=""
                            style={{ width: '140px', height: '40px', borderRadius: '8px' }}
                            onClick={getcaptcha}
                          />
                        </div>
                        <div style={{ margin: '30px' }}> </div>
                      </>
                    </LoginFormPage>
                  </div>
                </div>
                {/* <div className='modelDIv' style={{ color: "blue", fontSize: "16px", position: "absolute", width: "500px", bottom: "30px", right: "30px", textAlign: "right" }} onClick={() => {
            showModal()
          }}>
            软件下载
          </div> */}
              </>
            ) : (
              <PageLoading />
            )}
          </div>
        </div>
      )}
    </>
  );
};

export default Login;
